package cn.com.czpb.client.module.video.fragment;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.MyActivitymanager;
import cn.com.czpb.client.custorm.smartrefreshalayout.ClassHeader_other;
import cn.com.czpb.client.custorm.swiperefreshhelper.SwipeRefreshHelper_index;
import cn.com.czpb.client.model.base.BaseEntity;
import cn.com.czpb.client.model.event.PraiseEvent;
//import cn.com.gxrb.client.model.event.PublishEventForPublisher;
import cn.com.czpb.client.model.news.NewsBean;
import cn.com.czpb.client.model.news.NewsChannelBean;
import cn.com.czpb.client.model.news.NewsFlashEntity;
import cn.com.czpb.client.model.news.NewsListEntity;
import cn.com.czpb.client.module.news.NewsBaseFragment;
import cn.com.czpb.client.module.news.adapter.NewsItemListViewAdapterNew;
import cn.com.czpb.client.module.news.view.TopViewPagerView;
import cn.com.czpb.client.module.video.utils.VideoPlayerHelper;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.StatUtils;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/7/3.
 */

public class VideoItemFragment extends NewsBaseFragment implements OnRefreshListener, BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.recycler_newslist_id)
    RecyclerView recyclerNewslistId;
    @BindView(R.id.swipe_news_id)
    SmartRefreshLayout swipeNewsId;
    private NewsItemListViewAdapterNew adapter;
    private Boolean isFirstLoadFlash = true;
    private TopViewPagerView topViewPagerView;
    private int position = -1;
    private int page = 1;
    private int topnum = 0;
    private static final int pageSize = 15;//
    // 是否刷新最新数据
    private boolean mFlagRefresh;
    private boolean isNeedRefresh = false;
    private boolean isRefresh = false;//是否首次加载
    private NewsChannelBean channelbean;
    private String mTitle;
    SwipeRefreshHelper_index helper_1;
    private List<NewsBean> strList;
    @Override
    public int setMyContentView() {
        return R.layout.video_prlistview_new;
    }

    public static final VideoItemFragment newInstance(int position, NewsChannelBean newsChannelBean) {
        VideoItemFragment fragment = new VideoItemFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        bundle.putSerializable("bean", newsChannelBean);
        fragment.setArguments(bundle);
        return fragment;
    }

//    @Subscribe
//    public void onEventMainThread(PublishEventForPublisher event) {
//        LogUtils.e("published:"+event.getUid()+""+event.getPublished());
//        String uid = event.getUid();
//        swipeNewsId.autoRefresh();
//    }
    @Subscribe
    public void onEventMainThread(PraiseEvent event) {
        String nid = event.getNid();
        String praisenum = event.getPraisecount();
        LogUtils.e("event.getNid:"+nid+"event.getPraisecount:"+praisenum);
        LogUtils.e("topnum:"+topnum);
        LogUtils.e("adapter.getData.size:"+adapter.getData().size());
        for(int i=0;i<adapter.getData().size();i++){
            if(adapter.getData().get(i).getNid().equals(nid)){
                adapter.getData().get(i).setPraisecount(praisenum);
                adapter.notifyItemChanged(i+topnum);
                LogUtils.e("notifyitem:"+(i+topnum));
            }
        }
    }

    @Override
    public List<NewsBean> getNewsContent(){
        return strList;
    }
    @Override
    public void initView() {
        topnum = 0;
        channelbean = (NewsChannelBean) getArguments().getSerializable("bean");
        position = getArguments().getInt("position");

        helper_1 = new SwipeRefreshHelper_index(activity);

//        swipeNewsId.setColorSchemeColors(Color.parseColor("#4395DB"));
        final LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerNewslistId.setLayoutManager(layoutManager);
        initAdapter();
        swipeNewsId.setRefreshHeader(new ClassHeader_other(activity));
        swipeNewsId.setOnRefreshListener(this);
        mImmersionBar.statusBarDarkFont(true).init();
        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
//        recyclerNewslistId.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
//                // 当停止滑动时
//                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//                    //获取最后一个完全显示的ItemPosition ,角标值
//                    //获取 第一个条目
//                    int firstItem = manager.findFirstCompletelyVisibleItemPosition();
//                    LogUtils.i("firstitem-->"+firstItem);
//                    if (firstItem ==0){
//                        ((ZixunFragment)VideoItemFragment.this.getParentFragment()).toVisbility();
//                    }
                    //所有条目,数量值
//                }
//
//            }
//        });
    }
    private void initAdapter() {
        topViewPagerView = TopViewPagerView.Instance(activity);
        adapter = new NewsItemListViewAdapterNew(activity,null, true);

        adapter.setOnItemChildClickListener(this);
        adapter.setOnLoadMoreListener(this, recyclerNewslistId);
        recyclerNewslistId.setAdapter(adapter);
    }

    @Override
    public void initData() {
        strList = new ArrayList<>();
        LogUtils.i("position-->" + position);
        LogUtils.i("isNeedRefresh-->" + isNeedRefresh);
        if (0 == position || isNeedRefresh) {
            swipeNewsId.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mFlagRefresh = true;
                    getServerList();
                    getFlash();
                }
            }, 800);
            isRefresh = true;
            isNeedRefresh = false;
        }
    }

    public void init() {
        if (!isRefresh && null != recyclerNewslistId) {
            swipeNewsId.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mFlagRefresh = true;

                    getServerList();
                    getFlash();
                }
            }, 800);
            isRefresh = true;
            isNeedRefresh = false;
        }
    }

    public void setIsNeedRefresh() {
        isNeedRefresh = true;
    }

    public void setTitle(String title) {
        mTitle = title;
    }

    public String getTitle() {
        return mTitle;
    }


//    private NewsCancelDialog dialog;

    //点击时间
    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
        final NewsBean newsBean = (NewsBean) adapter.getItem(position);
        switch (view.getId()) {
            case R.id.newsItem_root:
                ////REFACTOR: 2017/8/18 添加浏览量bug
                VideoPlayerHelper.getInstance().stop();
                StatUtils.addCount(newsBean);
                MyActivitymanager.pushActivity(activity, newsBean, newsBean.getTid(), "newsitem", newsBean.getRvalue());
                LogUtils.e("rtype--" + newsBean.getRtype());
                break;
            case R.id.rl_root_id:
                VideoPlayerHelper.getInstance().play((ViewGroup) view,newsBean.getVideourl(),position);
//                VideoPlayerHelper.getInstance().play((ViewGroup) view,newsBean.getTitle(),position);
                break;
        }
    }
    /**
     * 不感兴趣
     *
     * @param tagid
     */
    private void notLikeNews(String nid, String tagid, final int position) {
        Map<String, String> map = new HashMap();
        map.put("nid", nid);
        map.put("device", DeviceUtils.getMyUUID(activity));
        map.put("tagid", tagid);
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
        }
        Factory.provideHttpService().newsLoseInterest(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BaseEntity>() {
                    @Override
                    public void call(BaseEntity entity) {
                        LogUtils.i("notLike-->" + entity.code);
                        adapter.remove(position);
                        adapter.notifyDataSetChanged();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("异常-->" + throwable.toString());
                    }
                });
    }

    //上拉加载更多
    @Override
    public void onLoadMoreRequested() {
        mFlagRefresh = false;
        page++;
        showDialog();
        getServerList();
    }

    /**
     * 获取新闻数据
     */
    public void getServerList() {
        LogUtils.i("init", "getNewslist");
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("tid", channelbean.getTid());
        map.put("Page", page + "");
        map.put("PageSize", pageSize + "");
        map.put("device", DeviceUtils.getMyUUID(activity));
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
            LogUtils.i("uid-->" + spu.getUser().getUid());
        }
        LogUtils.i("device-->" + DeviceUtils.getMyUUID(activity));
        Factory.provideHttpService()
                .newslist(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsListEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsListEntity entity) {

                        if ("200".equals(entity.code)) {
                            LogUtils.i("200--list>成功");
                            return true;
                        }
                        LogUtils.i("200--list>失败");
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsListEntity>() {
                    @Override
                    public void call(NewsListEntity entity) {
                        disMissDialog_index();
                        disMissDialog();
                        if (mFlagRefresh) {
                            if (swipeNewsId!=null) {
                                swipeNewsId.finishRefresh();
                            }
                        }

                        if ("200".equals(entity.code)) {
                            setListData(entity.data);
                            if (mFlagRefresh) {
                                LogUtils.i("200-->saveAll");
                                DataSupport.deleteAll(NewsBean.class);
                                DataSupport.saveAll(entity.data);
                            }

                        } else {
//                            TUtils.toast(entity.msg);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        if (mFlagRefresh) {
                            if (swipeNewsId!=null){
                                swipeNewsId.finishRefresh();
                                List<NewsBean> list = DataSupport.findAll(NewsBean.class);
                                setListData(list);
                            }
                        }
                        LogUtils.i("异常-->" + throwable.toString());
                        adapter.loadMoreFail();
                    }
                });
    }

    public void setListData(List<NewsBean> list) {

        if (mFlagRefresh) {
            strList.clear();
            adapter.setNewData(list);
            adapter.notifyDataSetChanged();
        } else {
            adapter.addData(list);
            adapter.notifyDataSetChanged();
            adapter.loadMoreComplete();
        }
        for (NewsBean bean :list
                ) {
            strList.add(bean);
        }
        LogUtils.i("size-->" + adapter.getData().size());
        if (list.size() < pageSize) {
            //关闭刷新
            adapter.loadMoreEnd(true);
        }
    }


    //    获取幻灯
    private void getFlash() {
        LogUtils.i("init", "getflash");
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("tid", channelbean.getTid());
        Factory.provideHttpService()
                .newsFlashlist(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsFlashEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsFlashEntity entity) {
                        LogUtils.i("flash--200-->" + entity.code);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsFlashEntity>() {
                               @Override
                               public void call(NewsFlashEntity entity) {
                                       if (isFirstLoadFlash) {
                                           LogUtils.i("flash--200-->成功-first");

                                           isFirstLoadFlash = false;
                                           isFirstLoadFlash = false;
                                           adapter.addHeaderView(topViewPagerView.getView());
                                           topnum = 1;
                                           topViewPagerView.reFreshFlashData(entity.data.flash);
                                       } else {
                                           topViewPagerView.reFreshFlashData(entity.data.flash);
                                       }
                               }
                           }, new Action1<Throwable>() {
                               @Override
                               public void call(Throwable throwable) {
                                   adapter.removeAllHeaderView();
                                   LogUtils.i("flash--200-->失败" + throwable.toString());
                               }
                           }
                );


    }

    @Override
    public void onPause() {

        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.e("NewsItemFragment onDestroy");
        EventBus.getDefault().unregister(this);
        helper_1.animationDrawable.stop();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 1;
                mFlagRefresh = true;
                showDialog_index();
                getFlash();
                getServerList();
            }
        }, 2000);
    }
}

